package com.gjs.freechat.web.acl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.gjs.freechat.web.business.WebUserManage;
import com.gjs.freechat.web.session.SessionManager;
import com.gjs.freechat.web.utils.MyWebUtils;

public class AuthenticateInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	WebUserManage webUserManage;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		//MyWebUtils.setBasePathToServletContext(request);
		boolean logined = SessionManager.isLogined(request);
		String servletPath = request.getServletPath();
		String contextPath = request.getContextPath();
		String redirect = null;
		
		if (!logined && servletPath.equals("/action/userManage/login")) {
			return super.preHandle(request, response, handler);
		}
		
		if (servletPath.equals("/login")) {
			if (logined)
				redirect = "/";
		} else {
			//logined = true; // test
			if (!logined) {
				redirect = "/login";
			}
		}
		if (redirect != null) {
			response.sendRedirect(contextPath + redirect);
			return false;
		}
		
		return super.preHandle(request, response, handler);
	}
}
